<script lang="ts" setup>
import PageTable from '@/components/q-table/component/page-table.vue';
import { usePageTable, useUpset } from '@/hooks';
import { AddUserParams, EditUserParams, IUser, api } from '@/service';
import { NButton } from 'naive-ui';

const tableRow = ref<IUser>();

const { dialog, message } = useFeedback(['dialog', 'message']);

const uniIdCo = uniCloud.importObject('uni-id-co', {
	customUI: true,
});

const { pageTableRef, columns, operations, tableRequest, refreshTable, getTableInstance } = usePageTable<IUser>({
	api: api.user.getPaginationUser,
	columns: [
		{ field: 'username', title: '用户名', searchFormItem: { type: 'n-input' } },
		{ field: 'nickname', title: '用户昵称', searchFormItem: { type: 'n-input' } },
		{ field: 'mobile', title: '手机号', searchFormItem: { type: 'n-input' } },
		{ field: 'email', title: '邮箱', searchFormItem: { type: 'n-input' } },
		{
			field: 'role',
			title: '用户角色',
			searchFormItem: {
				type: 'data-select',
				class: 'w-[140px]',
				permission: 'READ_UNI_ID_ROLES',
				ucloudDb: {
					collection: 'uni-id-roles',
					field: 'role_id as value,role_name as label',
				},
			},
		},

		{ field: 'register_date', title: '创建时间', cellRender: { name: 'Date' } },
		{ field: 'last_login_date', title: '最后登录时间', cellRender: { name: 'Date' } },
	],
	operations: [
		{
			label: '编辑',
			key: 'edit',
			show: (row) => !row.role?.includes('admin'),
		},
		{
			label: '删除',
			key: 'delete',
			type: 'error',
			show: (row) => !row.role?.includes('admin'),
		},
	],
});

const { formItems, handleAdd, handleEdit, setFormItem, removeFormItem } = useUpset<EditUserParams, string>({
	formItems: [
		{
			field: 'username',
			title: '用户名',
			type: 'n-input',
			validate: [{ required: true, message: '请输入用户名' }],
		},
		{
			field: 'nickname',
			title: '昵称',
			type: 'n-input',
			validate: [{ required: true, message: '请输入昵称' }],
		},
		{
			field: 'role',
			title: '用户角色',
			type: 'data-select',
			permission: 'READ_UNI_ID_ROLES',
			props: { multiple: true },
			ucloudDb: {
				collection: 'uni-id-roles',
				field: 'role_id as value,role_name as label',
			},
		},
		{
			field: 'dcloud_appid',
			title: '可登录应用',
			type: 'data-checkbox',
			ucloudDb: {
				collection: 'opendb-app-list',
				field: 'appid as value,name as label',
			},
		},
		{
			field: 'password',
			title: '初始密码',
			type: 'n-input',
			props: { placeholder: '请输入初始密码', type: 'password' },
			validate: [
				{ required: true, message: '请输入初始密码' },
				{ min: 6, message: '密码最少6位' },
			],
		},
		{ field: 'mobile', title: '手机号', type: 'n-input' },
		{ field: 'email', title: '邮箱', type: 'n-input' },
		{ field: 'status', title: '是否启用', type: 'n-switch', props: { checkedValue: 0, uncheckedValue: 1, defaultValue: 0 } },
	],
	api: (data) => (tableRow.value ? handleUpdateUser({ ...data, _id: tableRow.value._id }) : handleCreateUser(data)),
	success: () => {
		refreshTable();
	},
	title: '用户',
	modalOptions: {
		class: 'w-[500px]',
	},
});

const handleCreateUser = async (user: AddUserParams) => {
	try {
		const res = await uniIdCo.addUser({ ...user, authorizedApp: user.dcloud_appid });
		console.log(res);
		return res;
	} catch (error) {}
};

const handleUpdateUser = async (user: UpdateUserParams) => {
	try {
		const res = await uniIdCo.updateUser({ ...user, uid: user._id, authorizedApp: user.dcloud_appid });
		console.log(res);
		return res;
	} catch (error) {}
};

const handleAddUser = () => {
	handleAdd({});
};

const handleEditUser = (row: IUser) => {
	tableRow.value = row;
	setFormItem({
		field: 'password',
		value: {
			field: 'password',
			title: '重置密码',
			type: 'n-input',
			props: { placeholder: '请输入重置密码', type: 'password' },
			validate: [{ min: 6, message: '密码最少6位' }],
		},
	});
	handleEdit({
		initialData: row,
	});
};

const handleDeleteUser = (row: IUser) => {
	const deleteDialog = dialog.warning({
		title: '删除用户',
		content: '确定删除该用户吗？',
		positiveText: '确定',
		negativeText: '取消',
		onPositiveClick: async () => {
			try {
				deleteDialog.loading = true;
				const res = await api.user.deleteUser(row._id);
				message.success('删除成功');
				getTableInstance()?.remove(row);
			} catch (error) {
				message.error('删除失败');
			} finally {
				deleteDialog.loading = false;
			}
		},
	});
};

const handleSelect = (params: { key: string; row: IUser }) => {
	switch (params.key) {
		case 'add':
			handleAddUser();

			break;
		case 'edit':
			handleEditUser(params.row);
			break;
		case 'delete':
			handleDeleteUser(params.row);
			break;
	}
};

const handleRequested = () => {
	pageTableRef.value?.getTableInstance()?.setAllTreeExpand(true);
};
</script>
<template>
	<n-modal-provider>
		<page-wrap>
			<page-table
				ref="pageTableRef"
				:columns="columns"
				:operations="operations"
				:request="tableRequest"
				@requested="handleRequested"
				@operation-select="handleSelect"
			>
				<template #toolbarButtons>
					<div class="space-x-2">
						<n-button type="primary" @click="() => handleAddUser()">新增用户</n-button>
					</div>
				</template>
			</page-table>
		</page-wrap>
	</n-modal-provider>
</template>
